<template>
  <div class="page-container">
    <div class="control-container">
      <div class="left-panel shrink-panel" :class="isWide?'':'narrow'">
        <div class="shrink-btn-panel">
          <i :class="isWide?'el-icon-arrow-left':'el-icon-arrow-right'" @click="isWide = !isWide" />
        </div>
        <OutletTree
          v-if="isWide"
          @handleNodeClick="handleNodeClick"
        />
      </div>
      <div class="right-panel">
        <div class="search-panel">
          <el-form :inline="true" label-width="100">
            <el-form-item label="行业类型：">
              <el-select v-model="query.industryCategory">
                <el-option
                  v-for="(item, index) in industryCategorys"
                  :key="index + '_indusrty'"
                  :label="item.codeName"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="控制级别：">
              <el-select v-model="query.controlLevel">
                <el-option
                  v-for="(item, index) in controlLevels"
                  :key="index + '_contro'"
                  :label="item.codeName"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="排放类型：">
              <el-select v-model="query.emissionType">
                <el-option
                  v-for="(item, index) in emissionTypes"
                  :key="index + '_let'"
                  :label="item.codeName"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-button type="primary" @click="handleSelect">查询</el-button>
            <el-button v-show="coverage" type="primary" @click="handleChangeCoverage(false)">切换至客户图层</el-button>
            <el-button v-show="!coverage" type="primary" @click="handleChangeCoverage(true)">切换至排口图层</el-button>
          </el-form>
        </div>
        <div class="table-panel">
          <div id="map" style="height: calc(100vh - 325px)" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import OutletTree from '@/components/Tree/outletTree'
import BMap from 'BMap'
import { getDict } from '@/utils/dict'
import { parseTime } from '@/utils/index'
import { getEnterprise, getOutlet, getLastRealtime } from '@/api/base/map'
export default {
  name: 'Map',
  components: { OutletTree },
  data() {
    return {
      isWide: true,
      query: {
        industryCategory: '',
        controlLevel: '',
        emissionType: '',
        projectDepartmentId: null,
        enterpriseId: null,
        outletId: null,
        id: null
      },
      map: '',
      mapZoom: 9,
      // 行业
      industryCategorys: [],
      // 控制级别
      controlLevels: [],
      // 排放类型
      emissionTypes: [],
      coverage: false
    }
  },
  created() {
    this.$nextTick(() => {
      this.industryCategorys = getDict('e013')
      this.controlLevels = getDict('e014')
      this.emissionTypes = getDict('e012')
    })
    this.handleSelectEnterprise()
  },
  mounted() {
    this.initMap()
    // 自定义控件
    function TableControl() {
      // 默认停靠位置和偏移量
      // eslint-disable-next-line no-undef
      this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT
      this.defaultOffset = new BMap.Size(10, 10)
    }
    TableControl.prototype = new BMap.Control()
    TableControl.prototype.initialize = function(map) {
      // 创建一个DOM元素
      const div = document.createElement('div')
      div.appendChild(document.createTextNode('内江垃圾厂废水排放口统计'))
      // 设置样式
      div.style.cursor = 'pointer'
      div.style.padding = '7px 10px'
      div.style.backgroundColor = '#f0f3f5'
      div.style.height = '220px'
      div.style.width = '220px'
      // 添加DOM元素到地图中
      // map.getContainer().appendChild(div)
      // 将DOM元素返回
      return div
    }

    // 创建控件
    const tableControl = new TableControl()

    // 添加到地图当中
    this.map.addControl(tableControl)
  },
  methods: {
    // 初始化地图
    initMap() {
      // 创建Map实例
      this.map = new BMap.Map('map', { mapType: BMAP_HYBRID_MAP })
      // 初始化地图,设置中心点坐标和地图级别
      this.map.centerAndZoom(new BMap.Point(104.072242, 30.663711), this.mapZoom)
      // 设置地图显示的城市 此项是必须设置的
      this.map.setCurrentCity('成都')
      // 启用滚轮放大缩小，默认禁用
      this.map.enableScrollWheelZoom(true)
      // 启用地图惯性拖拽，默认禁用
      this.map.enableContinuousZoom(true)
      this.map.addControl(new BMap.MapTypeControl())
    },
    // 查询
    handleSelect() {
      if (this.coverage) {
        this.handleSelectOutlet()
      } else {
        this.handleSelectEnterprise()
      }
    },
    // 查询排口
    handleSelectOutlet() {
      getOutlet(this.query).then(res => {
        this.addMarkerPK(res.data.total)
      }).catch(() => {

      })
    },
    // 查询客户
    handleSelectEnterprise() {
      const query = JSON.parse(JSON.stringify(this.query))
      getEnterprise(query).then(res => {
        this.addMarkerKH(res.data.list)
      }).catch(() => {

      })
    },
    handleChangeCoverage(val) {
      this.clearQuery()
      this.coverage = val
      if (val) {
        this.handleSelectOutlet()
      } else {
        this.handleSelectEnterprise()
      }
    },
    // 点击树
    handleNodeClick(data) {
      this.clearQuery()
      if (this.coverage) {
        if (data.level === 1) {
          this.query.projectDepartmentId = data.id
        } else if (data.level === 2) {
          this.query.enterpriseId = data.id
        } else if (data.level === 3) {
          this.query.id = data.id
        }
        this.handleSelectOutlet()
      } else {
        if (data.level === 1) {
          this.query.projectDepartmentId = data.id
        } else if (data.level === 2) {
          this.query.id = data.id
        } else if (data.level === 3) {
          return false
        }
        this.handleSelectEnterprise()
      }
    },
    // 设置坐标
    addMarkerKH(data) {
      this.removeOverlay()
      data.forEach(item => {
        if (item.enterpriseLocation) {
          const gps = item.enterpriseLocation.split(',')
          const ponit = new BMap.Point(gps[0], gps[1])
          // 创建标记
          const marker = new BMap.Marker(ponit)
          this.map.addOverlay(marker)
          // 在地图上添加点标记
          marker.addEventListener('click', () => {
            var opts = {
              width: 300,
              height: 220,
              title: '基本信息'
            }
            var html = `<div style="font-size: 14px;">
                        <p>单位名称：${item.name}</p>
                        <p>联系电话：${item.contactInformation || ''}</p>
                        <p>单位地址：${item.enterpriseAddressDetails || ''}</p>
                      </div>`
            var infoWindow = new BMap.InfoWindow(html, opts)
            this.map.openInfoWindow(infoWindow, ponit)
          })
        }
      })
    },
    // 设置坐标
    addMarkerPK(data) {
      this.removeOverlay()
      data.forEach(item => {
        if (item.outletLocation) {
          const gps = item.outletLocation.split(',')
          const ponit = new BMap.Point(gps[0], gps[1])
          // 创建标记
          const marker = new BMap.Marker(ponit)
          this.map.addOverlay(marker)
          // 在地图上添加点标记
          marker.addEventListener('click', () => {
            let html = `<div style="font-size: 14px;">
                    <p>排放口名称：${item.outletName}</p>
                    <p>MN：${item.outletMn || ''}</p>
                    <p>地址详情：${item.addressDetails || ''}</p>
                  </div>`
            getLastRealtime({ id: item.id, lastRealtimeId: item.lastRealtimeId }).then(res => {
              if (res.code === 200 && res.data.lastRealtime) {
                const list = res.data.lastRealtime.row
                let h = 120
                if (list && list.length > 0) {
                  html += '<div style="display: flex;flex-wrap: wrap;align-items: center;justify-content: justify-content;">'
                  html += `<div style="flex: 92%;margin-bottom: 10px;font-size: 12px;">时间：${parseTime(res.data.lastRealtime.time, '{y}-{m}-{d} {h}:{i}:{s}')}</div>`
                  list.map(obj => {
                    html += `<div style="flex: 46%;margin-bottom: 10px;font-size: 12px;">${obj.name}(${obj.measurementUnit}): ${obj.val || ''}</div>`
                  })
                  html += '</div>'
                  h += 25 * (list.length / 2 + 1)
                }
                this.showMapWindow(ponit, html, 300, h)
              } else {
                this.showMapWindow(ponit, html, 300, 120)
              }
            }).catch(() => {
              this.showMapWindow(ponit, html, 300, 120)
            })
          // var opts = { width: 300,height: 150,title: '基本信息'}
          // var infoWindow = new BMap.InfoWindow(html, opts)
          // this.map.openInfoWindow(infoWindow, ponit)
          })
        }
      })
    },
    showMapWindow(ponit, html, width, height) {
      var opts = {
        width,
        height,
        title: '基本信息'
      }
      var infoWindow = new BMap.InfoWindow(html, opts)
      this.map.openInfoWindow(infoWindow, ponit)
    },
    // 清除标记
    removeOverlay() {
      this.map.clearOverlays()
    },
    clearQuery() {
      this.query = {
        industryCategory: '',
        controlLevel: '',
        emissionType: '',
        projectDepartmentId: null,
        enterpriseId: null,
        id: null
      }
    }
  }
}
</script>

<style lang='scss' scoped>
</style>
